<!DOCTYPE html>
<html lang="cn">
<head>
    <meta charset="UTF-8">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <title>数据上传中心</title>
    <style>
        /* 全局样式 */
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            color: #333;
            line-height: 1.6;
            background-color: #f5f7fa;
        }

        h1, h2, h3 {
            color: #2c3e50;
            margin-top: 0;
        }

        h1 {
            font-size: 2.2rem;
            margin-bottom: 1.5rem;
            padding-bottom: 0.5rem;
            border-bottom: 2px solid #3498db;
        }

        h2 {
            font-size: 1.5rem;
            margin-bottom: 1rem;
            color: #2980b9;
        }

        /* 卡片样式 */
        .card {
            border: 1px solid #ddd;
            padding: 25px;
            margin-bottom: 25px;
            border-radius: 10px;
            background: white;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            position: relative;
        }

        /* 文件项样式 */
        .file-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 12px;
            padding: 15px;
            background: white;
            border-radius: 8px;
            border: 1px solid #ddd;
            transition: all 0.3s ease;
        }

        .file-item:hover {
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            transform: translateY(-2px);
        }

        /* 文件操作样式 */
        .file-actions {
            display: flex;
            gap: 10px;
        }

        select, input[type="text"], input[type="file"] {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 14px;
            transition: border 0.3s;
        }

        select:focus, input[type="text"]:focus {
            outline: none;
            border-color: #3498db;
            box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
        }

        /* 按钮样式 */
        button {
            padding: 8px 16px;
            background-color: #3498db;
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
        }

        button:hover {
            background-color: #2980b9;
            transform: translateY(-1px);
        }

        button:active {
            transform: translateY(0);
        }

        /* 历史按钮样式 */
        .history-btn {
            position: absolute;
            right: 25px;
            top: 25px;
            background-color: #f39c12;
        }

        .history-btn:hover {
            background-color: #e67e22;
        }

        /* 上传区域样式 */
        .upload-section, .external-upload, .data-cleaning,
        .deduplication-history, .word-frequency-history {
            margin-top: 25px;
            padding: 20px;
            background: white;
            border-radius: 10px;
            border: 1px solid #ddd;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }

        /* 预览框样式 */
        .preview-box, .preview {
            margin-top: 20px;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 8px;
            display: none;
            max-height: 400px;
            overflow-y: auto;
            background: white;
            box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.05);
        }

        /* 代码块样式 */
        pre {
            white-space: pre-wrap;
            word-wrap: break-word;
            font-family: 'Consolas', 'Monaco', monospace;
            background: #f8f9fa;
            padding: 15px;
            border-radius: 5px;
            border-left: 3px solid #3498db;
        }

        /* 文件选择对话框样式 */
        .file-selection-dialog {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            align-items: center;
            justify-content: center;
        }

        .file-selection-content {
            background: white;
            padding: 30px;
            width: 50%;
            max-width: 500px;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
        }

        /* 选项卡导航样式 */
        .nav {
            display: flex;
            gap: 12px;
            margin-bottom: 25px;
            border-bottom: 1px solid #ddd;
            padding-bottom: 10px;
        }

        .nav button {
            padding: 10px 20px;
            background: none;
            color: #333;
            border: none;
            border-radius: 6px 6px 0 0;
            position: relative;
        }

        .nav button:hover {
            background: rgba(52, 152, 219, 0.1);
        }

        .nav button.active {
            color: #3498db;
            font-weight: bold;
        }

        .nav button.active::after {
            content: '';
            position: absolute;
            bottom: -11px;
            left: 0;
            width: 100%;
            height: 2px;
            background: #3498db;
        }

        /* 选项卡内容样式 */
        .tab-content {
            display: none;
            animation: fadeIn 0.3s ease;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        /* 弹窗样式 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            align-items: center;
            justify-content: center;
        }

        .modal-content {
            background: white;
            padding: 30px;
            width: 50%;
            max-width: 400px;
            border-radius: 10px;
            text-align: center;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
        }

        .modal-button {
            padding: 10px 20px;
            background: #2ecc71;
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            margin-top: 15px;
        }

        .modal-button:hover {
            background: #27ae60;
        }

        /* 标签样式 */
        label {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-right: 15px;
            cursor: pointer;
        }

        input[type="checkbox"] {
            width: 18px;
            height: 18px;
            accent-color: #3498db;
        }

        /* 文件选择按钮样式 */
        #fileSelectionButton {
            padding: 12px;
            border: 1px dashed #ddd;
            border-radius: 8px;
            text-align: center;
            cursor: pointer;
            margin-bottom: 15px;
            background: #f8f9fa;
            transition: all 0.3s;
        }

        #fileSelectionButton:hover {
            border-color: #3498db;
            background: rgba(52, 152, 219, 0.05);
        }

        /* 状态消息样式 */
        .status-message {
            padding: 10px;
            margin-top: 10px;
            border-radius: 5px;
        }

        .status-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .status-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        /* 时间戳样式 */
        .timestamp {
            font-size: 0.9em;
            color: #7f8c8d;
        }

        /* 文件信息样式 */
        .file-info {
            flex: 1;
        }

        .file-name {
            font-weight: bold;
            margin-bottom: 5px;
        }

        /* 加载动画样式 */
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 1s ease-in-out infinite;
            margin-left: 10px;
        }

        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .file-item {
                flex-direction: column;
                align-items: flex-start;
            }

            .file-actions {
                margin-top: 10px;
                width: 100%;
                justify-content: flex-end;
            }

            .nav {
                flex-direction: column;
                align-items: center;
            }

            .nav button {
                width: 100%;
                text-align: center;
                border-radius: 0;
            }

            .nav button.active::after {
                display: none;
            }
        }

        /* 新增的右上角按钮样式 */
        .header-buttons {
            position: absolute;
            top: 20px;
            right: 20px;
            display: flex;
            gap: 10px;
        }

        /* 清洗选项样式 */
        .cleaning-options {
            margin-top: 20px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 8px;
            border: 1px solid #ddd;
        }

        .options-group {
            display: flex;
            gap: 20px;
            flex-wrap: wrap;
        }

        label {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-right: 15px;
            cursor: pointer;
            padding: 8px 12px;
            border-radius: 6px;
            transition: all 0.3s;
        }

        label:hover {
            background: rgba(52, 152, 219, 0.1);
        }

        input[type="checkbox"] {
            width: 18px;
            height: 18px;
            accent-color: #3498db;
        }

        /* 选中时的样式 */
        input[type="checkbox"]:checked + span {
            color: #3498db;
            font-weight: bold;
        }

        /* 为选项添加背景色 */
        label {
            background: white;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
        }

        input[type="checkbox"]:checked + span {
            background: rgba(52, 152, 219, 0.1);
            border: 1px solid #3498db;
        }
    </style>
</head>
<body>
<div class="container">
    <!-- 新增的右上角按钮 -->
    <div class="header-buttons">
        <button class="header-button" onclick="goToHomePage()">返回主页</button>
        <button class="header-button" id="billListButton" onclick="goToBillList()">个人账单列表</button>
    </div>

    <h1>车辆数据上传中心</h1>

    <!-- 选项卡导航 -->
    <div class="nav">
        <button class="active" id="file-tab-btn" onclick="showTab('file-tab')">文件管理</button>
        <button id="cleaning-tab-btn" onclick="showTab('cleaning-tab')">数据清洗</button>
    </div>

    <!-- 文件选项卡内容 -->
    <div class="tab-content" id="file-tab" style="display: block;">
        <div class="card">
            <h2>文件列表</h2>
            <div class="file-list-container" id="fileList">
                <p class="loading-message">加载中...</p>
            </div>
            <div class="preview-box" id="previewBox"></div>
        </div>

        <div class="upload-section">
            <h2>本地上传</h2>
            <div class="upload-controls">
                <input class="file-input" id="localFileInput" type="file">
                <button class="upload-button" onclick="uploadToLocalHDFS()">
                    <i class="fas fa-upload"></i> 上传到HDFS
                </button>
            </div>
            <div class="status-message" id="uploadStatus"></div>
        </div>

        <div class="external-upload">
            <h2>外部文件收取</h2>
            <div class="external-controls">
                <input class="code-input" id="对接码" placeholder="请输入对接码" type="text">
                <button class="receive-button" onclick="receiveExternalFile()">
                    <i class="fas fa-download"></i> 接收文件
                </button>
            </div>
            <div class="status-message" id="externalStatus"></div>
        </div>
    </div>

    <!-- 清洗选项卡内容 -->
    <div class="tab-content" id="cleaning-tab">
        <div class="data-cleaning">
            <h2>数据清洗</h2>
            <div id="fileSelectionButton" onclick="showFileSelectionDialog()">
                <i class="fas fa-folder-open"></i> 请选择文件
            </div>
            <div class="file-list-container" id="cleaningFileList"></div>

            <div class="cleaning-options">
                <h3>清洗选项</h3>
                <div class="options-group">
                    <label><input id="deduplication" type="checkbox"> 去重处理</label>
                    <label><input id="wordFrequency" type="checkbox"> 词频统计</label>
                </div>
            </div>

            <button class="start-cleaning-button" onclick="startCleaning()">
                <i class="fas fa-magic"></i> 开始清洗
            </button>
            <div class="status-message" id="cleaningStatus"></div>
        </div>

        <div class="deduplication-history">
            <h2>去重历史记录</h2>
            <div class="history-list" id="deduplicationHistoryList"></div>
            <div class="preview" id="deduplicationPreviewBox"></div>
        </div>

        <div class="word-frequency-history">
            <h2>词频统计历史</h2>
            <div class="history-list" id="wordFrequencyHistoryList"></div>
            <div class="preview" id="wordFrequencyPreviewBox"></div>
        </div>
    </div>

    <!-- 文件选择弹出框 -->
    <div class="file-selection-dialog" id="fileSelectionDialog">
        <div class="file-selection-content">
            <h3>选择文件来源</h3>
            <p>请选择要清洗的文件来源</p>
            <div class="selection-options">
                <button class="selection-button" onclick="selectFileFromHDFS()">
                    <i class="fas fa-database"></i> 从HDFS获取
                </button>
                <button class="cancel-button" onclick="closeFileSelectionDialog()">
                    <i class="fas fa-times"></i> 取消
                </button>
            </div>
        </div>
    </div>

    <!-- 清洗成功弹窗 -->
    <div class="modal" id="successModal">
        <div class="modal-content">
            <div class="success-icon">
                <i class="fas fa-check-circle"></i>
            </div>
            <h3>数据清洗成功</h3>
            <p>文件已成功清洗并保存！</p>
            <button class="modal-button" onclick="closeSuccessModal()">确定</button>
        </div>
    </div>
</div>

<script>
    // 获取 URL 参数
    function getParameterByName(name, url) {
        url = url || window.location.href;
        name = name.replace(/[\[\]]/g, '\\$&');
        var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
            results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, ' '));
    }

    const uroot = getParameterByName('uroot');
    const root = parseInt(uroot, 10);

    var uid = getParameterByName('uid');
    const id = parseInt(uid, 10);

    var name = getParameterByName('uname');

    // 确保 uroot 的值正确
    if (!uroot) {
        console.error('uroot 参数未正确传递');
        alert('身份认证失败，请重新登录');
        window.location.href = 'login.html';
    }

    // 合并 window.onload 的逻辑
    window.addEventListener('load', function () {
        // 根据 uroot 的值动态修改按钮文本
        if (uroot === "8") {
            document.getElementById('billListButton').textContent = '账单列表';
        }

        // 初始化文件列表
        initFileList();

        // 初始化去重历史和词频统计历史
        initDeduplicationHistory();
        initWordFrequencyHistory();

        // 设置定时器，每30秒刷新一次
        setInterval(() => {
            initDeduplicationHistory();
            initWordFrequencyHistory();
        }, 30000); // 30秒刷新一次
    });

    // 新增的返回主页和账单列表功能
    function goToHomePage() {
        window.location.href = "main.html?uroot=" + encodeURIComponent(uroot) + "&uid=" + encodeURIComponent(id) + "&uname=" + encodeURIComponent(name);
    }

    function goToBillList() {
        if (uroot === "2" || uroot === "4") {
            window.location.href = "datauser.html?uroot=" + encodeURIComponent(uroot) + "&uid=" + encodeURIComponent(id) + "&uname=" + encodeURIComponent(name);
        } else if (uroot === "8") {
            window.location.href = "dataroot.html?uroot=" + encodeURIComponent(uroot) + "&uid=" + encodeURIComponent(id) + "&uname=" + encodeURIComponent(name);
        } else {
            alert("身份验证有误，请重新登录");
            window.location.href = "login.html"
        }
    }

    // 显示选项卡内容
    // 显示选项卡内容
    function showTab(tabId) {
        // 隐藏所有选项卡内容
        document.getElementById('file-tab').style.display = 'none';
        document.getElementById('cleaning-tab').style.display = 'none';

        // 移除所有按钮的 active 类
        document.getElementById('file-tab-btn').classList.remove('active');
        document.getElementById('cleaning-tab-btn').classList.remove('active');

        // 显示选中的选项卡内容
        document.getElementById(tabId).style.display = 'block';

        // 为选中的按钮添加 active 类
        if (tabId === 'file-tab') {
            document.getElementById('file-tab-btn').classList.add('active');
        } else if (tabId === 'cleaning-tab') {
            document.getElementById('cleaning-tab-btn').classList.add('active');
        }

        // 如果切换到数据清洗选项卡，重新加载去重历史和词频统计历史
        if (tabId === 'cleaning-tab') {
            initDeduplicationHistory();
            initWordFrequencyHistory();
        }
    }

    // 页面加载时默认显示文件选项卡
    window.onload = function () {
        showTab('file-tab');
    };

    // 存储选中的文件路径
    let cleaningSelectedFilePath = null;

    // 初始化文件列表
    async function initFileList() {
        try {
            const uid = getParameterByName('uid') || '1'; // 默认值为 1
            const response = await fetch(`http://127.0.0.1:8080/api/hdfs/files?limit=5&uid=${uid}`);
            const files = await response.json();
            renderFileList(files);
        } catch (error) {
            console.error('获取文件列表失败:', error);
        }
    }

    // 渲染文件列表
    function renderFileList(files) {
        const fileListElem = document.getElementById('fileList');
        fileListElem.innerHTML = '';

        if (files.length === 0) {
            fileListElem.innerHTML = '<p>暂无文件</p>';
            return;
        }

        // 保存当前已知的文件路径和对应的操作
        const savedActions = {};

        files.forEach(file => {
            // 将时间戳转换为可读的日期时间格式
            const uploadTime = new Date(file.uploadTime).toLocaleString();

            const fileItem = document.createElement('div');
            fileItem.className = 'file-item';

            // 从 localStorage 中读取保存的状态
            const savedAction = localStorage.getItem(`fileAction_${file.path}`);
            if (savedAction) {
                savedActions[file.path] = savedAction;
            }

            fileItem.innerHTML = `
                    <div>
                        <strong>${file.name}</strong>
                        <span>上传时间: ${uploadTime}</span>
                    </div>
                    <div class="file-actions">
                        <select onchange="handleFileAction('${file.path}', this.value, this)" data-file-path="${file.path}">
                            <option value="none">无操作</option>
                            <option value="preview">预览</option>
                            <option value="delete">删除</option>
                            <option value="download">下载</option>
                            <option value="insertToMySQL">插入MySQL</option>
                        </select>
                    </div>
                `;
            fileListElem.appendChild(fileItem);
        });

        // 渲染完成后，恢复下拉框状态
        Object.entries(savedActions).forEach(([filePath, action]) => {
            const selectElement = document.querySelector(`select[data-file-path="${filePath}"]`);
            if (selectElement) {
                selectElement.value = action;
            }
        });
    }

    // 处理文件操作
    function handleFileAction(filePath, action, selectElement) {
        // 保存状态到 localStorage
        localStorage.setItem(`fileAction_${filePath}`, action);

        // 先隐藏所有预览框
        hideAllPreviews();

        switch (action) {
            case 'preview':
                togglePreview(filePath);
                break;
            case 'delete':
                deleteFile(filePath);
                break;
            case 'download':
                downloadFile(filePath);
                break;
            case 'insertToMySQL':
                insertToMySQL(filePath);
                break;
            case 'none':
                // 当选择“无操作”时，隐藏预览框
                hideAllPreviews();
                break;
        }
    }

    // 隐藏所有预览框
    function hideAllPreviews() {
        document.getElementById('previewBox').style.display = 'none';
        document.getElementById('deduplicationPreviewBox').style.display = 'none';
        document.getElementById('wordFrequencyPreviewBox').style.display = 'none';
    }

    // 显示文件选择弹出框
    function showFileSelectionDialog() {
        document.getElementById('fileSelectionDialog').style.display = 'block';
    }

    // 关闭文件选择弹出框
    function closeFileSelectionDialog() {
        document.getElementById('fileSelectionDialog').style.display = 'none';
    }

    async function selectFileFromHDFS() {
        closeFileSelectionDialog();
        try {
            const uid = getParameterByName('uid') || '1'; // 默认值为 '1'
            const response = await fetch(`http://127.0.0.1:8080/api/hdfs/files?limit=10&uid=${uid}`);
            const files = await response.json();

            // 确保返回的数据是数组
            if (!Array.isArray(files)) {
                console.error('返回的数据不是数组:', files);
                return;
            }

            renderCleaningFileList(files);
        } catch (error) {
            console.error('获取文件列表失败:', error);
        }
    }

    // 渲染数据清洗文件列表
    function renderCleaningFileList(files) {
        const cleaningFileListElem = document.getElementById('cleaningFileList');
        cleaningFileListElem.innerHTML = '';

        if (files.length === 0) {
            cleaningFileListElem.innerHTML = '<p>暂无文件</p>';
            return;
        }

        files.forEach(file => {
            const fileItem = document.createElement('div');
            fileItem.className = 'file-item';
            fileItem.innerHTML = `
                <div>
                    <strong>${file.name}</strong>
                </div>
                <div class="file-actions">
                    <button onclick="selectCleaningFile('${file.path}', '${file.name}')">选择</button>
                </div>
            `;
            cleaningFileListElem.appendChild(fileItem);
        });
    }

    // 选择数据清洗文件
    function selectCleaningFile(path, name) {
        cleaningSelectedFilePath = path;
        document.getElementById('fileSelectionButton').textContent = `已选择文件: ${name}`;
    }

    // 数据清洗
    async function startCleaning() {
        const deduplication = document.getElementById('deduplication').checked;
        const wordFrequency = document.getElementById('wordFrequency').checked;

        if (!cleaningSelectedFilePath) {
            alert('请选择要清洗的文件');
            return;
        }

        try {
            const response = await fetch('http://127.0.0.1:8080/api/hdfs/clean', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({
                    filePath: cleaningSelectedFilePath,
                    deduplication: deduplication,
                    wordFrequency: wordFrequency
                })
            });

            const result = await response.json();
            if (result.status === 'success') {
                // 显示成功弹窗
                document.getElementById('successModal').style.display = 'block';
                initDeduplicationHistory();
                initWordFrequencyHistory();
            } else {
                document.getElementById('cleaningStatus').textContent = '数据清洗成功'
            }
        } catch (error) {
            // document.getElementById('cleaningStatus').textContent = '数据清洗失败: ' + error.message;
        }
    }

    // 关闭成功弹窗
    function closeSuccessModal() {
        document.getElementById('successModal').style.display = 'none';
    }

    async function initDeduplicationHistory() {
        try {
            const uid = getParameterByName('id') || '1'; // 默认值为 '1'
            const response = await fetch(`http://127.0.0.1:8080/api/hdfs/deduplication-history?limit=5&uid=${uid}`);
            const history = await response.json();
            renderDeduplicationHistory(history);
        } catch (error) {
            console.error('获取去重历史失败:', error);
        }
    }

    // 渲染去重历史
    function renderDeduplicationHistory(history) {
        const historyListElem = document.getElementById('deduplicationHistoryList');
        historyListElem.innerHTML = '';

        if (history.length === 0) {
            historyListElem.innerHTML = '<p>暂无去重记录</p>';
            return;
        }

        history.forEach(record => {
            const recordItem = document.createElement('div');
            recordItem.className = 'file-item';
            recordItem.innerHTML = `
                    <div>
                        <strong>${record.name}</strong>
                        <span>清洗时间: ${new Date(record.uploadTime).toLocaleString()}</span>
                    </div>
                    <div class="file-actions">
                        <select onchange="handleDeduplicationAction('${record.path}', this.value, this)">
                            <option value="none">无操作</option>
                            <option value="preview">预览</option>
                            <option value="delete">删除</option>
                            <option value="download">下载</option>
                        </select>
                    </div>
                `;
            historyListElem.appendChild(recordItem);
        });
    }

    // 处理去重记录操作
    function handleDeduplicationAction(filePath, action, selectElement) {
        // 先隐藏所有预览框
        hideAllPreviews();

        switch (action) {
            case 'preview':
                previewDeduplicationDetail(filePath);
                break;
            case 'delete':
                deleteDeduplicationRecord(filePath);
                break;
            case 'download':
                downloadDeduplicationRecord(filePath);
                break;
        }
    }

    // 初始化词频统计历史
    async function initWordFrequencyHistory() {
        try {
            const uid = getParameterByName('id') || '1'; // 默认值为 '1'
            const response = await fetch(`http://127.0.0.1:8080/api/hdfs/word-frequency-history?limit=5&uid=${uid}`);
            const history = await response.json();
            renderWordFrequencyHistory(history);
        } catch (error) {
            console.error('获取词频统计历史失败:', error);
        }
    }

    // 渲染词频统计历史
    function renderWordFrequencyHistory(history) {
        const historyListElem = document.getElementById('wordFrequencyHistoryList');
        historyListElem.innerHTML = '';

        if (history.length === 0) {
            historyListElem.innerHTML = '<p>暂无词频统计记录</p>';
            return;
        }

        history.forEach(record => {
            const recordItem = document.createElement('div');
            recordItem.className = 'file-item';
            recordItem.innerHTML = `
                    <div>
                        <strong>${record.name}</strong>
                        <span>清洗时间: ${new Date(record.uploadTime).toLocaleString()}</span>
                    </div>
                    <div class="file-actions">
                        <select onchange="handleWordFrequencyAction('${record.path}', this.value, this)">
                            <option value="none">无操作</option>
                            <option value="preview">预览</option>
                            <option value="delete">删除</option>
                            <option value="download">下载</option>
                            <option value="insertToMySQL">插入MySQL</option>
                        </select>
                    </div>
                `;
            historyListElem.appendChild(recordItem);
        });
    }

    // 处理词频统计记录操作
    function handleWordFrequencyAction(filePath, action, selectElement) {
        // 先隐藏所有预览框
        hideAllPreviews();

        switch (action) {
            case 'preview':
                previewWordFrequencyDetail(filePath);
                break;
            case 'delete':
                deleteWordFrequencyRecord(filePath);
                break;
            case 'download':
                downloadWordFrequencyRecord(filePath);
                break;
            case 'insertToMySQL':
                insertWordFrequencyToMySQL(filePath);
                break;
        }
    }

    // 预览去重详情
    async function previewDeduplicationDetail(filePath) {
        const previewBox = document.getElementById('deduplicationPreviewBox');
        previewBox.style.display = 'block';

        try {
            const response = await fetch(`http://127.0.0.1:8080/api/hdfs/preview?path=${filePath}`);
            const content = await response.text();
            // 限制预览内容的长度
            const previewContent = content.length > 10000 ? content.substring(0, 10000) + '...' : content;

            previewBox.innerHTML = `<h3>去重详情</h3>
                                       <pre>${previewContent}</pre>`;
        } catch (error) {
            console.error('预览去重详情失败:', error);
            previewBox.innerHTML = '<p>预览失败</p>';
        }
    }

    // 预览词频统计详情
    async function previewWordFrequencyDetail(filePath) {
        const previewBox = document.getElementById('wordFrequencyPreviewBox');
        previewBox.style.display = 'block';

        try {
            const response = await fetch(`http://127.0.0.1:8080/api/hdfs/preview?path=${filePath}`);
            const content = await response.text();
            // 限制预览内容的长度
            const previewContent = content.length > 10000 ? content.substring(0, 10000) + '...' : content;

            previewBox.innerHTML = `<h3>词频统计详情</h3>
                                       <pre>${previewContent}</pre>`;
        } catch (error) {
            console.error('预览词频统计详情失败:', error);
            previewBox.innerHTML = '<p>预览失败</p>';
        }
    }

    // 删除去重记录
    async function deleteDeduplicationRecord(filePath) {
        try {
            const response = await fetch(`http://127.0.0.1:8080/api/hdfs/delete?path=${filePath}`, {method: 'DELETE'});
            if (response.ok) {
                alert('记录已删除');
                initDeduplicationHistory();
            }
        } catch (error) {
            console.error('删除记录失败:', error);
        }
    }

    // 删除词频统计记录
    async function deleteWordFrequencyRecord(filePath) {
        try {
            const response = await fetch(`http://127.0.0.1:8080/api/hdfs/delete?path=${filePath}`, {method: 'DELETE'});
            if (response.ok) {
                alert('记录已删除');
                initWordFrequencyHistory();
            }
        } catch (error) {
            console.error('删除记录失败:', error);
        }
    }

    // 切换预览框显示/隐藏
    let currentPreviewPath = null;

    async function togglePreview(filePath) {
        const previewBox = document.getElementById('previewBox');
        if (currentPreviewPath === filePath && previewBox.style.display === 'block') {
            previewBox.style.display = 'none';
            currentPreviewPath = null;
        } else {
            // 先隐藏所有预览框
            hideAllPreviews();

            try {
                const response = await fetch(`http://127.0.0.1:8080/api/hdfs/preview?path=${filePath}`);
                const content = await response.text();
                // 限制预览内容的长度
                const previewContent = content.length > 10000 ? content.substring(0, 10000) + '...' : content;

                // 获取文件的详细信息，包括上传时间
                const fileDetailResponse = await fetch(`http://127.0.0.1:8080/api/hdfs/file-detail?path=${filePath}`);
                const fileDetail = await fileDetailResponse.json();
                const uploadTime = new Date(fileDetail.uploadTime).toLocaleString();

                previewBox.innerHTML = `<h3>文件预览</h3>
                                           <p>上传时间: ${uploadTime}</p>
                                           <pre>${previewContent}</pre>`;
                previewBox.style.display = 'block';
                currentPreviewPath = filePath;
            } catch (error) {
                console.error('预览文件失败:', error);
            }
        }
    }

    // 删除文件
    async function deleteFile(filePath) {
        try {
            const response = await fetch(`http://127.0.0.1:8080/api/hdfs/delete?path=${filePath}`, {method: 'DELETE'});
            if (response.ok) {
                alert('文件已删除');
                initFileList();
            }
        } catch (error) {
            console.error('删除文件失败:', error);
        }
    }

    // 下载文件
    async function downloadFile(filePath) {
        window.location.href = `http://127.0.0.1:8080/api/hdfs/download?path=${filePath}`;
    }

    // 下载去重记录
    async function downloadDeduplicationRecord(filePath) {
        window.location.href = `http://127.0.0.1:8080/api/hdfs/download?path=${filePath}`;
    }

    // 下载词频统计记录
    async function downloadWordFrequencyRecord(filePath) {
        window.location.href = `http://127.0.0.1:8080/api/hdfs/download?path=${filePath}`;
    }

    async function uploadToLocalHDFS() {
        const fileInput = document.getElementById('localFileInput');
        const formData = new FormData();
        formData.append('file', fileInput.files[0]);

        // 从 URL 中获取 uid
        const uid = getParameterByName('id') || '1'; // 默认值为 '1'

        try {
            const response = await fetch(`/api/hdfs/uploads?uid=${uid}`, { // 传递 uid 参数
                method: 'POST',
                body: formData
            });

            const result = await response.json();
            if (result.status === 'success') {
                document.getElementById('uploadStatus').textContent = '文件上传成功!';
                initFileList();
            } else {
                document.getElementById('uploadStatus').textContent = '上传失败: ' + result.message;
            }
        } catch (error) {
            document.getElementById('uploadStatus').textContent = '上传失败: ' + error.message;
        }
    }

    // 接收外部文件
    async function receiveExternalFile() {
        const code = document.getElementById('对接码').value;
        const tempFilePath = localStorage.getItem('tempFilePath');

        if (!tempFilePath) {
            alert('暂存文件路径无效');
            return;
        }

        try {
            const response = await fetch('http://127.0.0.1:8080/api/hdfs/receive', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({code, tempPath: tempFilePath})
            });

            const result = await response.json();
            if (result.status === 'success') {
                alert('文件已上传到HDFS和本地目录');
                document.getElementById('externalStatus').textContent = '文件接收成功';
                localStorage.removeItem('tempFilePath'); // 清除暂存路径
                initFileList();
            } else {
                alert('接收失败: ' + result.message);
                document.getElementById('externalStatus').textContent = '接收失败: ' + result.message;
            }
        } catch (error) {
            console.error('接收文件失败:', error);
            alert('接收失败: ' + error.message);
            document.getElementById('externalStatus').textContent = '接收失败: ' + error.message;
        }
    }

    async function insertToMySQL(filePath) {
        if (!confirm('确定要将此文件内容插入MySQL吗？')) return;

        try {
            const response = await fetch('http://127.0.0.1:8080/api/hdfs/insert-to-mysql', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({filePath})
            });

            const result = await response.text();
            alert(result);
        } catch (error) {
            alert('插入失败: ' + error.message);
        }
    }

    async function insertWordFrequencyToMySQL(filePath) {
        if (!confirm('确定要将此词频统计结果插入MySQL吗？')) return;

        try {
            const response = await fetch('http://127.0.0.1:8080/api/hdfs/insert-word-frequency-to-mysql', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({filePath})
            });

            const result = await response.text();
            alert(result);
        } catch (error) {
            alert('插入失败: ' + error.message);
        }
    }

    // 自动刷新文件列表 xiexiaoming
    setInterval(initFileList, 3000);

    // 页面加载时初始化
    window.onload = function () {
        initFileList();
        initDeduplicationHistory();
        initWordFrequencyHistory();

        // 设置定时器，每30秒刷新一次
        setInterval(() => {
            initDeduplicationHistory();
            initWordFrequencyHistory();
        }, 30000); // 30秒刷新一次
    };
</script>
</body>
</html>